import { defineStore } from "pinia";
import { ref } from "vue";
export const useAppStore = defineStore("app", () => {
  let isCollapse = ref(false);
  const changeCollapse = () => {
    isCollapse.value = !isCollapse.value;
  };
  return { isCollapse, changeCollapse };
});
export const useTagStore = defineStore("tag", () => {
  // 多页签数组
  let tags = ref([
    {
      path: "/home",
      name: "首页",
      meta: { title: "首页" },
    },
  ]);
  // 执行保存的页签数组
  let cacheList = ref([]);
  // 新增页签
  const addTag = (val) => {
    if (!tags.value.some((item) => item.path === val.path)) {
      tags.value.push(val);
    }
  };
  // 关闭页签
  const delTag = (router, val, currentPath) => {
    if (currentPath == val.path) {
      let endPath = tags.value[tags.value.length - 1].path;
      let twoPath = tags.value[tags.value.length - 2].path;
      let path = endPath == currentPath ? twoPath : endPath;
      router.push(path);
    }
    const delIndex = tags.value.findIndex((item) => item.path === val.path);
    if (delIndex !== -1) {
      tags.value.splice(delIndex, 1);
    }
    delCache(val.name);
  };
  // 关闭其他页签
  const delOther = (ind) => {
    let arr = [];
    tags.value.forEach((item, index) => {
      if (item.meta.title == "首页" || index == ind) {
        arr.push(item);
      } else {
        item.name && delCache(item.name);
      }
      if (index == tags.value.length - 1) {
        console.log(arr, "查看arr");

        tags.value = arr;
      }
    });
  };
  // 关闭全部页签
  const delAll = () => {
    tags.value = tags.value.slice(0, 1);
    cacheList.value = [];
  };
  // 添加keep-alive的name
  const addCache = (val) => {
    if (!cacheList.value.includes(val)) {
      cacheList.value.push(val);
    }
  };
  // 删除keep-alive的name
  const delCache = (val) => {
    const delIndex = cacheList.value.findIndex((item) => item === val);
    if (delIndex !== -1) {
      cacheList.value.splice(delIndex, 1);
    }
  };
  return {
    tags,
    addTag,
    delTag,
    delOther,
    delAll,
    cacheList,
    addCache,
    delCache,
  };
});
